package com.mcptt.notify.presence;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import com.cloudptt.api.product.log.Log;

public class PresenceParser
{
    public static final String Key = "<presence xmlns=\"";
    private static final String Name = "presence";
    private static final String Name_Entity = "entity";
    private static final String Name_Pid = "p-id";

    private String entity = null;


    private Tuple tuple = null;
    private String pid = null;

    public void parse(String xmlStr) throws IOException,JDOMException
    {
	SAXBuilder builder = new SAXBuilder();//实锟斤拷JDOM锟斤拷锟斤拷锟斤拷  
	ByteArrayInputStream strIs = new  ByteArrayInputStream(xmlStr.getBytes());
	Document document = builder.build(strIs);
	Element rootEle = document.getRootElement();//锟斤拷酶锟斤拷诘锟�<bookstore> 
	if(rootEle == null)
	{
	    return;
	}
	entity = rootEle.getAttributeValue(Name_Entity);

	List<Element> list = rootEle.getChildren();//锟斤拷酶锟斤拷诘锟斤拷锟接节碉拷  
	for(Element elem:list) 
	{
	    String name = elem.getName();
	    Log.debug(this.getClass(), "name = " + name);
	    if(name == null
		    || name.length() <= 0)
	    {
		return;
	    }
	    if(name.equals(Tuple.Name))
	    {
		tuple = new Tuple();
		tuple.parse(elem);
	    }
	    else if(name.equals(Name_Pid))
	    {
		pid = elem.getText();
	    }
	}  
    }

    public List<Affiliation> getAffiliationList()
    {
	if(tuple != null
		&& tuple.getStatus() != null)
	{
	    return tuple.getStatus().getAffiliationList();
	}
	return null;
    } 
    
    public String getEntity()
    {
        return entity;
    }

    public String toString()
    {
	StringBuffer strBuf = new StringBuffer();
	strBuf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
	strBuf.append("<").append(Name).append(" xmlns=\"urn:ietf:params:xml:ns:pidf\" xmlns:mcpttPI10=\"urn:3gpp:ns:mcpttPresInfo:1.0\" ");
	strBuf.append(Name_Entity).append("=\"").append(entity).append("\" >");
	strBuf.append(tuple);
	strBuf.append("<mcpttPI10:").append(Name_Pid).append(">");
	strBuf.append(pid);
	strBuf.append("</mcpttPI10:").append(Name_Pid).append(">");
	strBuf.append("</").append(Name).append(">");

	return strBuf.toString();
    }
}
